package myJs.tool

import myJs.myPkg.jquery.$
import org.scalajs.dom.window
import org.scalajs.dom.window.localStorage
import shared.pojo.Role
import slinky.web.html.s
import myJs.Implicits._
import typings.csstype.csstypeStrings

import scala.scalajs.js
import scala.scalajs.js.{Date, |}

/**
 * Created by yz on 8/12/2022
 */
object Tool {

  val positiveDoubleRegexp=js.RegExp("^(0|[1-9]\\d*)(\\.\\d+)?$")
  val pattern = "yyyy-mm-dd"

  val confirmButtonClass = "btn-danger"
  val cancelButtonClass = "green"

  def getRoleOp = {
    val roleStr = localStorage.getItem("role")
    if (roleStr == null) {
      None
    } else {
      Some(Role.withNameInsensitive(roleStr))
    }
  }

  def getAccount = {
    localStorage.getItem("account")
  }
  def getUserId = {
    localStorage.getItem("user_id").toInt
  }

  def selectLeft: Unit = {
    val idInfo = window.location.href.replaceAll(".*/#/", "").
      replaceAll("\\?.*$", "")
    selectLeft(idInfo)
  }

  def selectLeft(idInfo: String): Unit = {
    val tmpIdInfos = idInfo.split("/").toList
    val idInfos = tmpIdInfos.size match {
      case 2 | 3 => tmpIdInfos.drop(1)
      case _ => tmpIdInfos
    }
    val mainId = idInfos.head
    val liId = idInfos.getOrElse(1, "")
    val menuContainer = $(".page-sidebar ul")
    menuContainer.children("li.active").removeClass("active")
    menuContainer.children("li").children("ul").hide()
    $(s"#${mainId} ul>li").removeClass("open")
    $(s"#${mainId}").addClass("active")
    if (liId.nonEmpty) {
      $(s"#${mainId} ul").show()
      $(s"#${mainId} #${liId}").addClass("open")
    }
  }

  def b2Display(b: Boolean) = {
    if (b) csstypeStrings.block else csstypeStrings.none
  }

  def timeBefore = (dateStr: String, dbDateStr: String) => {
    val date = new Date(dateStr)
    val dbDate = new Date(dbDateStr)
    dbDate.setUTCHours(0, 0, 0, 0)
    date.getTime() <= dbDate.getTime()
  }

  def timeAfter = (dateStr: String, dbDateStr: String) => {
    val date = new Date(dateStr)
    val dbDate = new Date(dbDateStr)
    dbDate.setUTCHours(0, 0, 0, 0)
    date.getTime() >= dbDate.getTime()
  }


}
